﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace JiJiDownApp.Lib
{
    public class OpenerFolder
    {
        [DllImport("shell32.dll")]
        private static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, IntPtr[]? apidl, uint dwFlags);

        [DllImport("shell32.dll")]
        private static extern void ILFree(IntPtr pidl);

        [DllImport("shell32.dll")]
        private static extern IntPtr ILCreateFromPathW([MarshalAs(UnmanagedType.LPWStr)] string pszPath);

        public static void OpenFolderNative(string folderPath)
        {
            IntPtr pidl = ILCreateFromPathW(folderPath);
            if (pidl != IntPtr.Zero)
            {
                try
                {
                    SHOpenFolderAndSelectItems(pidl, 0, null, 0);
                }
                finally
                {
                    ILFree(pidl);
                }
            }
        }

        public static void OpenFolderCmd(string folderPath)
        {
            Process cmd = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = "cmd",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardInput = true
                }
            };
            cmd.Start();
            int processId = cmd.Id;
            Debug.WriteLine("PID: {0}", processId);
            cmd.StandardInput.Write("start " + folderPath + "\r\n");
            cmd.StandardInput.Write("exit\r\n");
            cmd = null;

            try
            {
                Process isCmdStillThere = Process.GetProcessById(processId);
            }
            catch (Exception errorQueryingProcess)
            {
                Debug.Assert(errorQueryingProcess.Message == "Process with an Id of " + processId + " is not running.");

            }
        }
    }
}
